﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class reciboCliente : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bPFactura.Attributes.Add("OnClick", "javascript:popUpFactura();");
        lbFecha.Text = System.DateTime.Now.ToString();
        if (!IsPostBack)
        {
            SqlDataSource1.SelectParameters.Clear();
            SqlDataSource1.SelectCommand = "SELECT rccc.cod_factura_ventas, fvd.n_cuota, rccc.monto, rccc.iva_5, rccc.iva_10, rccc.excentas FROM recibo_cc_cuota AS rccc INNER JOIN factura_ventas_cc_detalle AS fvd ON rccc.cod_factura_ventas_cc_detalle = fvd.cod_factura_ventas_cc_detalle WHERE rccc.cod_recibo_cc = @cod_recibo_cc ORDER BY rccc.cod_factura_ventas";
            SqlDataSource1.SelectParameters.Add("cod_recibo_cc", TypeCode.Int32, "0");
            SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.Text;
            GridView1.DataBind();
        }
    }

     protected void guardar_cabeceraReciboCC()
      {
          String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
          SqlConnection conexion = new SqlConnection(cadena);
                  
          
              if (estadoCabeceraRecibo.Text == "finalizado")
              {
                  
                      try
                      {

                          SqlCommand comando = new SqlCommand();
                          conexion.Open();

                          comando.Connection = conexion;
                          comando.CommandType = System.Data.CommandType.StoredProcedure;
                          comando.CommandText = "insertar_recibo_cc";
                          comando.Parameters.AddWithValue("@cod_cliente", nombreTex.Text);
                          comando.Parameters.AddWithValue("@cod_funcionario", 1);
                          comando.Parameters.AddWithValue("@cod_caja", cajaTex.Text);
                          SqlDataReader reader = comando.ExecuteReader();
                         // GridView1.DataBind();

                          conexion.Close();
                          estadoCabeceraRecibo.Text = "activo";
                      }
                      catch (Exception error)
                      {
                          Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");
                      }
                  }
                  
                }
              


    

      protected void guardar_cabeceraFactura()
      {
          
          
          String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
          SqlConnection conexion = new SqlConnection(cadena);
          
          
          if(cod_recibo_cc.Text=="null"){
            try
            {
                conexion.Open();
                SqlCommand Cod_Factura = new SqlCommand();
                Cod_Factura.CommandText = "select coalesce(max(cod_recibo_cc),0) from recibo_cc";
                Cod_Factura.Connection = conexion;
                Cod_Factura.CommandType = CommandType.Text;
                SqlDataReader read1 = Cod_Factura.ExecuteReader();
                read1.Read();
                cod_recibo_cc.Text = read1.GetValue(0).ToString();
                L_Nro_Recibo.Text = cod_recibo_cc.Text;
            }
            catch (Exception error)
            {
                Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");
            }
            finally
            {
                conexion.Close();
            }
          }

          SqlCommand comando = new SqlCommand();
          conexion.Open();
          comando.Connection = conexion;
          comando.CommandType = System.Data.CommandType.StoredProcedure;
          comando.CommandText = "insertar_recibo_cc_factura";
          comando.Parameters.AddWithValue("@cod_recibo_cc", cod_recibo_cc.Text );
          comando.Parameters.AddWithValue("@cod_factura_ventas", facturaTex.Text);
          SqlDataReader reader = comando.ExecuteReader();
          conexion.Close();
          

          }

      protected void guardar_cuota()
      {
            
            String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection conexion = new SqlConnection(cadena);
            try
            {
                conexion.Open();
                SqlCommand codigo_recibo_cc_factura = new SqlCommand();
                codigo_recibo_cc_factura.CommandText = "select coalesce(max(cod_recibo_cc_factura),0) from recibo_cc_factura";
                codigo_recibo_cc_factura.Connection = conexion;
                codigo_recibo_cc_factura.CommandType = CommandType.Text;
                SqlDataReader read1 = codigo_recibo_cc_factura.ExecuteReader();
                read1.Read();
                cod_recibo_cc_factura.Text= read1.GetValue(0).ToString();
            }
            catch (Exception error)
            {
                Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");
            }
            finally
            {
                conexion.Close();
            }
          
                  SqlCommand comando = new SqlCommand();
                  conexion.Open();
                  comando.Connection = conexion;
                  comando.CommandType = System.Data.CommandType.StoredProcedure;
                  comando.CommandText = "insertar_recibo_cc_cuota";
                  comando.Parameters.AddWithValue("@cod_recibo_cc_factura",cod_recibo_cc_factura.Text);
                  comando.Parameters.AddWithValue("@cod_recibo_cc", cod_recibo_cc.Text);
                  comando.Parameters.AddWithValue("@cod_factura_ventas_cc_detalle", cod_facturaD.Text);
                  comando.Parameters.AddWithValue("@cod_factura_ventas", facturaTex.Text);
                  SqlDataReader reader = comando.ExecuteReader();
                  conexion.Close();
      
      }
      protected void AgregarFactura_Click(object sender, ImageClickEventArgs e)
      {
          if ((nombreTex.Text == "" ) || (facturaTex.Text=="") || (n_cuotaText.Text=="")||(cod_facturaD.Text == "" ))
          {
              LError_Factura.Visible = true;
              LError_factD.Visible=true;
              LError_Cliente.Visible = true;
              LError_Texto.Visible = true;
                 }
          else
          {

              LError_Factura.Visible =false;
              LError_factD.Visible=false;
              LError_Cliente.Visible = false;
              LError_Texto.Visible = false;
   
              guardar_cabeceraReciboCC();
              guardar_cabeceraFactura();
              guardar_cuota();
              SqlDataSource1.SelectParameters.Clear();
              SqlDataSource1.SelectCommand = "SELECT rccc.cod_factura_ventas, fvd.n_cuota, rccc.monto, rccc.iva_5, rccc.iva_10, rccc.excentas FROM recibo_cc_cuota AS rccc INNER JOIN factura_ventas_cc_detalle AS fvd ON rccc.cod_factura_ventas_cc_detalle = fvd.cod_factura_ventas_cc_detalle WHERE rccc.cod_recibo_cc = @cod_recibo_cc ORDER BY rccc.cod_factura_ventas";
              SqlDataSource1.SelectParameters.Add("cod_recibo_cc", TypeCode.Int32, cod_recibo_cc.Text);
              SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.Text;
              GridView1.DataBind();
              //Sumar el importe total en la casilla de importe
              String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
              SqlConnection conexion = new SqlConnection(cadena);
              try
              {
                  conexion.Open();
                  SqlCommand importe_total = new SqlCommand();
                  importe_total.CommandText = "select SUM(monto) from recibo_cc_cuota where cod_recibo_cc=" + cod_recibo_cc.Text;
                  importe_total.Connection = conexion;
                  importe_total.CommandType = CommandType.Text;
                  SqlDataReader importe_total_reader = importe_total.ExecuteReader();
                  importe_total_reader.Read();
                  totalTex.Text = importe_total_reader.GetValue(0).ToString();
                  importe_total_reader.Close();

              }
              catch (Exception error)
              {
                  Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");

              }
              finally
              {
                  conexion.Close();
              }
              compararDeuda();

          }
              
      }
          


      protected void compararDeuda()
      {
          String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
          SqlConnection conexion = new SqlConnection(cadena);
          try
          {
              conexion.Open();
              SqlCommand importe_total = new SqlCommand();
              importe_total.CommandText = "select SUM(cantidad) from pagos_recibo_cc where cod_recibo_cc=" + cod_recibo_cc.Text;
              importe_total.Connection = conexion;
              importe_total.CommandType = CommandType.Text;
              SqlDataReader importe_total_reader = importe_total.ExecuteReader();
              importe_total_reader.Read();
              valorTemp.Text = importe_total_reader.GetValue(0).ToString();
              importe_total_reader.Close();
              if (valorTemp.Text == "")
              {
                  valorTemp.Text = "0";
              }
              valorRestanteText.Text = Convert.ToString((Convert.ToInt32(totalTex.Text) - Convert.ToInt32(valorTemp.Text)));

          }
          catch (Exception error)
          {
              Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");
             
          }
          finally
          {
              conexion.Close();
          }

      }


      protected void agregarPago_Click(object sender, ImageClickEventArgs e)
      {
          if ((Convert.ToInt32(montoText.Text)) > (Convert.ToInt32(valorRestanteText.Text)))
          {
              Page.RegisterStartupScript("alerta", "<SCRIPT> alerta('El valor supera al importe de la factura') </SCRIPT>");
          }
          else
          {
              String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
              SqlConnection conexion = new SqlConnection(cadena);
              try
              {
                  SqlCommand comando = new SqlCommand();
                  conexion.Open();
                  comando.Connection = conexion;
                  comando.CommandType = System.Data.CommandType.StoredProcedure;
                  comando.CommandText = "insertar_pagos_recibo_cc";
                  comando.Parameters.AddWithValue("@cod_recibo_cc", Convert.ToInt32(cod_recibo_cc.Text));
                  comando.Parameters.AddWithValue("@cod_forma_a_pagar", dCod_FormaAPagar.Text);
                  comando.Parameters.AddWithValue("@cod_banco", dCod_Banco.Text);
                  comando.Parameters.AddWithValue("@cantidad", montoText.Text);
                  comando.Parameters.AddWithValue("@cuenta_bancaria", cuentaBancariaText.Text);
                  comando.Parameters.AddWithValue("@numero", numeroTarjetaText.Text);
                  SqlDataReader reader = comando.ExecuteReader();
                  compararDeuda();
                  cuentaBancariaText.Text = "";
                  montoText.Text = "";
                  numeroTarjetaText.Text = "";

              }
              catch (Exception error)
              {
                  Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");
              }
              finally
              {
                  conexion.Close();
              }
          }
      }
      protected void finalizarPago_Click(object sender, ImageClickEventArgs e)
      {
          if (montoText.Text == "")
          {
              montoText.Text = "0";
          }
          if ((Convert.ToInt32(montoText.Text)) > (Convert.ToInt32(valorRestanteText.Text)))
          {
              Page.RegisterStartupScript("alerta", "<SCRIPT> alerta('El valor supera al importe de la factura') </SCRIPT>");
          }
          if ((Convert.ToInt32(montoText.Text)) == (Convert.ToInt32(valorRestanteText.Text)))
          {
              String cadena = (String)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
              SqlConnection conexion = new SqlConnection(cadena);
              try
              {
                  SqlCommand comando = new SqlCommand();
                  conexion.Open();
                  comando.Connection = conexion;
                  comando.CommandType = System.Data.CommandType.StoredProcedure;
                  comando.CommandText = "cobrar";
                  comando.Parameters.AddWithValue("@cod_recibo_cc", Convert.ToInt32(cod_recibo_cc.Text));
                  SqlDataReader reader = comando.ExecuteReader();

              }
              catch (Exception error)
              {
                  Page.RegisterStartupScript("alerta", "<SCRIPT> alerta(" + error.Message.ToString() + ") </SCRIPT>");
              }
              finally
              {
                  conexion.Close();
              }
              
              estadoCabeceraRecibo.Text = "finalizado";
              cod_recibo_cc.Text = "null";
              nombreTex.Text = "";
              facturaTex.Text = "";
              n_cuotaText.Text = "";
              cod_facturaD.Text = "";
              GridView1.Columns.Clear();
              GridView1.DataBind();
              
              
          }
          if ((Convert.ToInt32(montoText.Text)) < (Convert.ToInt32(valorRestanteText.Text)))
          {
              Page.RegisterStartupScript("alerta", "<SCRIPT> alerta('El pago de la factura aun no fue totalizada') </SCRIPT>");
          }
      }


    }

    
  

